from platform import uname

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)


# 数据库的配置变量
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'root'
PASSWORD = '123456'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
# 把连接到数据库的参数设置到 app 中
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False


# 1.创建数据库连接
db = SQLAlchemy(app)

# 2.创建模型类
class User(db.Model):
	__tablename__ = 't_user'
	id = db.Column(db.Integer, primary_key = True, autoincrement = True)
	uname = db.Column(db.String(50))
	pwd = db.Column(db.String(50))

	def __repr__(self):
		return 'User(id:{}, uname:{}, pwd:{})'.format(self.id, self.uname, self.pwd)


# 创建数据库的表
# with app.app_context():
# 	db.create_all()
@app.route('/')
def hello_world():  # put application's code here
	return render_template('index.html')

@app.route('/create')
def create():
	name = request.args.get('name')
	pwd = request.args.get('pwd')
	# 插入到数据库
	user = User(uname = name, pwd = pwd)
	db.session.add(user)
	db.session.commit()
	return '添加数据成功'

@app.route('/select')
def query():
	# 查询数据库
	user = User.query.filter(User.id == 1).first()
	return user.__repr__()

@app.route('/delete')
def delete():
	name = request.args.get('name')
	user = User.query.filter(User.uname == name).first()
	db.session.delete(user)
	db.session.commit()
	return '删除数据成功'


if __name__ == '__main__':
	app.run()
